<template>
  <div style="margin-top: 40px">
    <el-row :gutter="10" style="margin-top: 20px;display: flex;align-items: flex-start">
      <el-col :span="9">
        <el-image :src="currentSku.urls" fit="cover" style="width:100%;border-radius: 10px;aspect-ratio: 1 / 1;"></el-image>
      </el-col>
      <el-col :span="15" style="display:flex;flex-wrap: wrap;margin-left: 50px;align-items: flex-start">
        <div style="display:flex;justify-content: space-between;width: 100%">
          <div class="spu-name" style="height: 50px;width: 80%;font-weight: bolder;font-size: 20px;">
            {{ spu.name }}
            {{ spu.detail ? spu.detail : '' }}
          </div>
          <div style="width: 10%;margin-left: 5%;margin-right: 5%">
            <el-button  size="medium" round icon="el-icon-arrow-left" @click="$router.go(-1)">返回</el-button>
          </div>
        </div>
        <div style="height: 50px;width: 100%;color: #ff662d;display: flex;align-items: center;">
          <div v-if="currentSku.salePrice<currentSku.price" style="color: #555555;display: flex;align-items: center">
            <span style="font-size: 14px">原价 ￥</span>
            <span style="font-weight: bolder;font-size: 18px;text-decoration: line-through">{{currentSku.price}}</span>
          </div>
          <div style="display: flex;align-items: center;margin-left: 10px">
            <span style="font-size: 14px" v-text="currentSku.salePrice<currentSku.price?'折后价   ￥':'优惠价格   ￥'"></span>
            <span style="font-weight: bolder;font-size: 28px;">{{currentSku.salePrice}}</span>
            <span style="font-size: 12px;font-style: italic;margin-left: 5px">起</span>
          </div>
          <div style="margin-left: 100px">
            <span style="font-size: 16px;color: #50607a">已售 {{
                spu.sales < 100 ? spu.sales : Math.floor(spu.sales / 100) * 100
              }}<span v-show="spu.sales>=100" style="font-size: 10px">+</span> 双</span>
          </div>
        </div>
        <div style="margin-top: 10px;display: flex;flex-wrap: wrap">
          <div style="display: flex;align-items: center;width: 50%">
            <span style="font-size: 16px;font-weight: bold;color: #555555;margin-right: 20px;width: 40px;flex-shrink: 0">材质: </span>
            <div style="display: flex;flex-wrap: wrap;align-items: center;height: auto;overflow: hidden">
              <el-tag size="medium" style="margin: 3px 3px" effect="light" v-for="material in spu.attribute.material" :key="material">{{ material }}</el-tag>
            </div>
          </div>
          <div style="display: flex;align-items: center;width: 50%">
            <span style="font-size: 16px;font-weight: bold;color: #555555;margin-right: 20px;width: 40px;flex-shrink: 0">保障: </span>
            <div style="display: flex;flex-wrap: wrap;align-items: center;height: auto;overflow: hidden">
              <el-tag size="medium" style="margin: 3px 3px" effect="light" v-for="material in spu.attribute.assurance" :key="material">{{ material }}</el-tag>
            </div>
          </div>
          <div style="display: flex;align-items: center;width: 50%">
            <span style="font-size: 16px;font-weight: bold;color: #555555;margin-right: 20px;width: 40px;flex-shrink: 0">功能: </span>
            <div style="display: flex;flex-wrap: wrap;align-items: center;height: auto;overflow: hidden">
              <el-tag size="medium" style="margin: 3px 3px" effect="light" v-for="material in spu.attribute.function" :key="material">{{ material }}</el-tag>
            </div>
          </div>
          <div style="display: flex;align-items: center;width: 50%">
            <span style="font-size: 16px;font-weight: bold;color: #555555;margin-right: 20px;width: 70px;flex-shrink: 0">适用人群: </span>
            <div style="display: flex;flex-wrap: wrap;align-items: center;height: auto;overflow: hidden">
              <el-tag size="medium" style="margin: 3px 3px" effect="light" v-for="material in spu.attribute.people" :key="material">{{ material }}</el-tag>
            </div>
          </div>
        </div>
<!--        颜色尺码列表-->
        <div style="display: flex;align-items: center;width: 100%;margin-top: 20px">
          <span style="font-size: 16px;font-weight: bold;color: #555555;margin-right: 20px;width: 40px;flex-shrink: 0">颜色: </span>
          <div style="display: flex;flex-wrap: wrap;align-items: center;height: auto;overflow: hidden">
            <el-radio :size="colorList.length>7?'mini':'small'" v-model="currentColor" border style="margin: 3px 3px"
                      v-for="color in colorList" :key="color" :label="color" @change="selectColor(color)">
              {{ color }}
            </el-radio>
          </div>
        </div>
        <div style="display: flex;align-items: center;width: 100%;margin-top: 20px">
          <span style="font-size: 16px;font-weight: bold;color: #555555;margin-right: 20px;width: 40px;flex-shrink: 0">尺码: </span>
          <div style="display: flex;flex-wrap: wrap;align-items: center;height: auto;overflow: hidden">
            <el-radio :size="sizeList.length>7?'mini':'small'" v-model="currentSize" border style="margin: 3px 3px"
                      @change="selectSize(size)"
                      v-for="size in sizeList" :key="size" :label="size" :disabled="isSizeDisabled(size)">
              {{ size }}
            </el-radio>
          </div>
        </div>
<!--        数量、加入购物车、立即购买按钮-->
        <div style="width: 100%;margin-top: 30px;display: flex;justify-content: space-between;align-items: center">
          <div style="width: 38%;display: flex;align-items: center">
            <span style="font-size: 16px;font-weight: bold;color: #555555;margin-right: 20px;width: 40px;flex-shrink: 0">数量: </span>
            <el-input-number style="width: 65%" :min="1" :max="currentSku.stock" size="small"
                             v-model="count"></el-input-number>
          </div>
          <div style="width: 12%">
            <span v-show="this.currentSku.stock&&this.count >= this.currentSku.stock" style="color: #ff5116" class="shake">库存不足</span>
            <span v-show="!currentSku.stock" style="color: #797979;font-weight: bold">缺 货</span>
          </div>
          <el-button-group style="width: 50%">
            <el-button :disabled="!currentSku.stock" :style="currentSku.stock?{background: '#ff5f0a'}:{background: 'rgba(126,123,123,0.6)'}"
                       round style="width: 50%;color: honeydew" @click="addToCart">加入购物车</el-button>
            <el-button :disabled="!currentSku.stock" :style="currentSku.stock?{background: '#1395ff'}:{background: 'rgba(126,123,123,0.6)'}"
                       round style="width: 50%;color: honeydew" @click="buyNow">立即购买</el-button>
          </el-button-group>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="10" style="margin-top: 50px;display: flex;align-items: flex-start;">
      <el-col :span="14">
        <div style="color: #11192d;font-weight: bolder;font-size: 20px;width:100%;height: 40px;
        margin-bottom: 10px;border-bottom: 1px solid rgba(98,98,98,0.21);">用户评价</div>
        <el-radio-group v-model="commentCode" size="small" @input="selectComment">
          <el-radio-button label="3">全部</el-radio-button>
          <el-radio-button label="2">好评</el-radio-button>
          <el-radio-button label="1">中评</el-radio-button>
          <el-radio-button label="0">差评</el-radio-button>
        </el-radio-group>
        <div style="width: 100%;margin-top: 40px">
          <CommentCard v-for="comment in commentList" :key="comment.id" :comment="comment"/>
          <el-empty v-show="!commentList.length" description="暂无评价"></el-empty>
        </div>
      </el-col>
      <el-col :span="10"  style="display:flex;flex-wrap: wrap;margin-left: 50px;align-items: flex-start;position: sticky;top: 100px">
        <el-collapse-transition>
          <div v-show="showFloatInfoDiv">
            <div class="spu-name" style="height: 50px;width: 100%;font-weight: bolder;font-size: 20px;">
              {{ spu.name }}
              {{ spu.detail ? spu.detail : '' }}
            </div>
            <div style="height: 50px;width: 100%;color: #ff662d;display: flex;align-items: center;">
              <div v-if="currentSku.salePrice<currentSku.price" style="color: #555555;display: flex;align-items: center">
                <span style="font-size: 14px">原价 ￥</span>
                <span style="font-weight: bolder;font-size: 18px;text-decoration: line-through">{{currentSku.price}}</span>
              </div>
              <div style="display: flex;align-items: center;margin-left: 10px">
                <span style="font-size: 14px" v-text="currentSku.salePrice<currentSku.price?'折后价   ￥':'优惠价格   ￥'"></span>
                <span style="font-weight: bolder;font-size: 28px;">{{currentSku.salePrice}}</span>
                <span style="font-size: 12px;font-style: italic;margin-left: 5px">起</span>
              </div>
              <div style="margin-left: 100px">
            <span style="font-size: 16px;color: #50607a">已售 {{
                spu.sales < 100 ? spu.sales : Math.floor(spu.sales / 100) * 100
              }}<span v-show="spu.sales>=100" style="font-size: 10px">+</span> 双</span>
              </div>
            </div>
            <div style="margin-top: 10px;display: flex;flex-wrap: wrap">
              <div style="display: flex;align-items: center;width: 50%">
                <span style="font-size: 16px;font-weight: bold;color: #555555;margin-right: 20px;width: 40px;flex-shrink: 0">材质: </span>
                <div style="display: flex;flex-wrap: wrap;align-items: center;height: auto;overflow: hidden">
                  <el-tag size="medium" style="margin: 3px 3px" effect="light" v-for="material in spu.attribute.material" :key="material">{{ material }}</el-tag>
                </div>
              </div>
              <div style="display: flex;align-items: center;width: 50%">
                <span style="font-size: 16px;font-weight: bold;color: #555555;margin-right: 20px;width: 40px;flex-shrink: 0">保障: </span>
                <div style="display: flex;flex-wrap: wrap;align-items: center;height: auto;overflow: hidden">
                  <el-tag size="medium" style="margin: 3px 3px" effect="light" v-for="material in spu.attribute.assurance" :key="material">{{ material }}</el-tag>
                </div>
              </div>
              <div style="display: flex;align-items: center;width: 50%">
                <span style="font-size: 16px;font-weight: bold;color: #555555;margin-right: 20px;width: 40px;flex-shrink: 0">功能: </span>
                <div style="display: flex;flex-wrap: wrap;align-items: center;height: auto;overflow: hidden">
                  <el-tag size="medium" style="margin: 3px 3px" effect="light" v-for="material in spu.attribute.function" :key="material">{{ material }}</el-tag>
                </div>
              </div>
              <div style="display: flex;align-items: center;width: 50%">
                <span style="font-size: 16px;font-weight: bold;color: #555555;margin-right: 20px;width: 70px;flex-shrink: 0">适用人群: </span>
                <div style="display: flex;flex-wrap: wrap;align-items: center;height: auto;overflow: hidden">
                  <el-tag size="medium" style="margin: 3px 3px" effect="light" v-for="material in spu.attribute.people" :key="material">{{ material }}</el-tag>
                </div>
              </div>
            </div>
            <!--        颜色尺码列表-->
            <div style="display: flex;align-items: center;width: 100%;margin-top: 20px">
              <span style="font-size: 16px;font-weight: bold;color: #555555;margin-right: 20px;width: 40px;flex-shrink: 0">颜色: </span>
              <div style="display: flex;flex-wrap: wrap;align-items: center;height: auto;overflow: hidden">
                <el-radio :size="colorList.length>7?'mini':'small'" v-model="currentColor" border style="margin: 3px 3px"
                          v-for="color in colorList" :key="color" :label="color" @change="selectColor(color)">
                  {{ color }}
                </el-radio>
              </div>
            </div>
            <div style="display: flex;align-items: center;width: 100%;margin-top: 20px">
              <span style="font-size: 16px;font-weight: bold;color: #555555;margin-right: 20px;width: 40px;flex-shrink: 0">尺码: </span>
              <div style="display: flex;flex-wrap: wrap;align-items: center;height: auto;overflow: hidden">
                <el-radio :size="sizeList.length>7?'mini':'small'" v-model="currentSize" border style="margin: 3px 3px"
                          @change="selectSize(size)"
                          v-for="size in sizeList" :key="size" :label="size" :disabled="isSizeDisabled(size)">
                  {{ size }}
                </el-radio>
              </div>
            </div>
            <!--        数量、加入购物车、立即购买按钮-->
            <div style="width: 100%;margin-top: 30px;display: flex;justify-content: space-between;align-items: center">
              <div style="width: 42%;display: flex;align-items: center">
                <span style="font-size: 16px;font-weight: bold;color: #555555;margin-right: 20px;width: 40px;flex-shrink: 0">数量: </span>
                <el-input-number style="width: 60%" :min="1" :max="currentSku.stock" size="mini"
                                 v-model="count"></el-input-number>
              </div>
              <div style="width: 8%">
                <span v-show="this.currentSku.stock&&this.count >= this.currentSku.stock" style="color: #ff5116" class="shake">库存不足</span>
                <span v-show="!currentSku.stock" style="color: #797979;font-weight: bold">缺货</span>
              </div>
              <el-button-group style="width: 50%">
                <el-button :disabled="!currentSku.stock" @click="addToCart" :style="currentSku.stock?{background: '#ff5f0a'}:{background: 'rgba(126,123,123,0.6)'}" round style="width: 50%;color: honeydew">加入购物车</el-button>
                <el-button :disabled="!currentSku.stock" @click="buyNow" :style="currentSku.stock?{background: '#1395ff'}:{background: 'rgba(126,123,123,0.6)'}" round style="width: 50%;color: honeydew">立即购买</el-button>
              </el-button-group>
            </div>
            <div style="margin-top: 30px;width: 60%">
              <el-image :src="currentSku.urls" fit="cover" style="width:100%;border-radius: 10px;aspect-ratio: 1 / 1;"></el-image>
            </div>
          </div>
        </el-collapse-transition>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {getSkuListFront} from "@/api/goods";
import {getUser} from "@/utils/storage";
import CommentCard from "@/components/common/CommentCard.vue";
import {getComment} from "@/api/sComment";
import {addSCart} from "@/api/sCart";

export default {
  name: "Goods",
  components: {CommentCard},
  data() {
    return {
      spu:{
        attribute:{}
      },
      user: {},
      currentSku: {
        urls:''
      },
      count:1,
      skuList:[],
      sizeList:[],
      colorList:[],
      currentSize:'',
      currentColor:'',
      //3全部，2好评，1中评，0差评
      commentCode:3,
      commentList:[],
      lowStock:false,//库存不足
      nonSock:false,//缺货
    }
  },
  //父组件监听滚动事件，当超过一定阈值后，显示右侧浮动sku信息
  computed:{
    showFloatInfoDiv(){
      return this.$store.state.spu.showFloatInfoDiv
    },
  },
  created() {
    this.user = getUser()
    // this.spu.id = this.$route.params.id
    this.spu = JSON.parse(JSON.stringify(this.$store.state.spu.selectedSpu))
    this.load()
    this.selectComment()
    document.title = `${this.spu.name} - 独特魅力，细节呈现`
  },
  methods: {
    load() {
      getSkuListFront(this.spu.id).then(res => {
        if (res.code === '0') {
          this.skuList = res.data
          //第一个sku就是当前颜色和尺码下第一个可选的sku
          this.currentSku = this.skuList[0]
          // 提取skuList中的size和color到Set中，以消除重复
          const sizeSet = new Set(this.skuList.map(sku => sku.attribute.size))
          const colorSet = new Set(this.skuList.map(sku => sku.attribute.color))
          this.colorList = Array.from(colorSet)
          this.sizeList = Array.from(sizeSet).sort()
          //默认设置当前颜色为第一个sku的颜色
          this.currentColor = this.skuList[0].attribute.color
          //设置当前尺码为当前颜色下第一个可选的尺码
          this.currentSize = this.getSizesByColor(this.currentColor)[0]
          //设置当前sku为当前颜色和尺码下第一个可选的sku
          // this.currentSku = this.getSkuByColorAndSize(this.currentColor, this.currentSize)
          console.log(this.currentSku)
        }
      })
    },
    // isColorDisabled(color){
    //   //获取当前尺码下的所有颜色,判断传入的颜色是否在其中,不存在返回true
    //   return !this.getColorsBySize(this.currentSize).includes(color)
    // },
    // getColorsBySize(size) {
    //   const filteredSkus = this.filterSkuByAttr('size', size);
    //   return filteredSkus.length > 0
    //       ? Array.from(new Set(filteredSkus.map(sku => sku.attribute.color)))
    //       : []
    // },
    //获取当前颜色下的所有尺码,判断传入的尺码是否在其中,不存在返回true
    isSizeDisabled(size){
      return !this.getSizesByColor(this.currentColor).includes(size)
    },
    //获取某个颜色下的所有尺码
    getSizesByColor(color) {
      const filteredSkus = this.filterSkuByAttr('color', color);
      return filteredSkus.length > 0
          ? Array.from(new Set(filteredSkus.map(sku => sku.attribute.size)))
          : []
    },
    //选中某个颜色
    selectColor(color) {
      this.count = 1
      this.currentColor = color
      if (this.isSizeDisabled(this.currentSize)) {
        //如果当前尺码不可用,则将尺码重置为当前颜色下第一个可选的尺码
        this.currentSize = this.getSizesByColor(color)[0]
      }
      this.currentSku = this.getSkuByColorAndSize(color, this.currentSize)
      console.log(this.currentSku)
   },
    //选中某个尺码
    selectSize(size) {
      this.count = 1
      this.currentSize = size
      this.currentSku = this.getSkuByColorAndSize(this.currentColor, size)
      console.log(this.currentSku)
   },
    getSkuByColorAndSize(color, size) {
      return this.skuList.find(sku => sku.attribute.color === color && sku.attribute.size === size);
    },
    //通过attribute过滤出具有value的Sku
    filterSkuByAttr(attribute, value) {
      return this.skuList.filter(sku => sku.attribute[attribute] === value);
    },
    selectComment(){
      getComment(this.spu.id,this.commentCode).then(res => {
        if (res.code === '0') {
          this.commentList = res.data
        }
      })
    },
    addToCart() {
      const cartObj = {
        userId: this.user.id,
        spuId: this.spu.id,
        count: this.count,
        price: this.currentSku.price,
        salePrice: this.currentSku.salePrice,
        skuUrl: this.currentSku.urls,
        spuName: this.spu.name,
        skuAttribute: JSON.stringify(this.currentSku.attribute),
        skuId:this.currentSku.id
      }
      //减库存如果写在.then中会响应不及时使得库存为负数
      this.currentSku.stock -= this.count
      addSCart(cartObj).then(res => {
        if (res.code === '0') {
          this.$message({
            message: '添加成功',
            type: 'success'
          })
        }else {
          this.currentSku.stock += this.count
        }
      })
    },
    buyNow() {
      const cartObj = {
        userId: this.user.id,
        spuId: this.spu.id,
        skuId:this.currentSku.id,
        count: this.count,
        price: this.currentSku.price,
        salePrice: this.currentSku.salePrice,
        skuUrl: this.currentSku.urls,
        spuName: this.spu.name,
        skuAttribute: JSON.stringify(this.currentSku.attribute)
      }
      this.$store.commit('sCart/pushSelectedList',cartObj)
      this.$router.push('/front/preOrder')
    },
  },
};
</script>

<style scoped>
@keyframes shake {
  0% { transform: translate(1px, 1px) rotate(0deg); }
  10% { transform: translate(-1px, -2px) rotate(-1deg); }
  20% { transform: translate(-3px, 0px) rotate(1deg); }
  30% { transform: translate(3px, 2px) rotate(0deg); }
  40% { transform: translate(1px, -1px) rotate(1deg); }
  50% { transform: translate(-1px, 2px) rotate(-1deg); }
  60% { transform: translate(-3px, 1px) rotate(0deg); }
  70% { transform: translate(3px, 1px) rotate(-1deg); }
  80% { transform: translate(-1px, -1px) rotate(1deg); }
  90% { transform: translate(1px, 2px) rotate(0deg); }
  100% { transform: translate(1px, -2px) rotate(-1deg); }
}

.shake {
  animation: shake 0.5s linear; /* 根据需要调整持续时间、速度曲线和是否无限循环 */
  display: inline-block; /* 确保元素可以动画 */
}
.spu-name {
  overflow: hidden;
  display: -webkit-box; /* 将对象作为弹性伸缩盒子模型显示 */
  -webkit-line-clamp: 2; /* 行数，值可以改，表示展示X行后多余的缩略展示 */
  -webkit-box-orient: vertical; /* 设置或检索伸缩盒对象的子元素的排列方式 */
  word-break: break-all;
}
</style>
